import { WebSocketServer } from "ws";
import Mock from "mockjs";
// 生成随机数据
const Random = Mock.Random;
Random.date("yyyy-MM-dd");
Random.city();
Random.id();
function getData() {
  const result = Mock.mock({
    "data|30": [
      {
        id: "@id",
        date: "@date",
        address: "@city",
        "number|1-10000": 1,
      },
    ],
  });
  return result.data;
}

const wss = new WebSocketServer({
  port: 4000,
});

function timeout(ws) {
  setTimeout(() => {
    sendMessage(ws);
    timeout(ws);
  }, 15000);
}

function sendMessage(ws) {
  const data = getData();
  ws.send(JSON.stringify(data));
}

// 客户端连接事件：一旦客户端连接上ws服务器，就会触发这个事件
wss.on("connection", (ws) => {
  ws.on("message", (data) => {
    if (data.toString() === "ping") {
      ws.send("pong");
    }
  });
  sendMessage(ws);
  timeout(ws);
});
